package com.feilong.edgeAI.utils;

import static android.content.Context.BATTERY_SERVICE;
import static android.content.Context.CAMERA_SERVICE;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.admin.DevicePolicyManager;
import android.bluetooth.BluetoothAdapter;
import android.content.ComponentName;
import android.content.ContentResolver;
import android.content.Context;
import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.content.res.Configuration;
import android.database.Cursor;
import android.hardware.camera2.CameraAccessException;
import android.hardware.camera2.CameraCharacteristics;
import android.hardware.camera2.CameraManager;
import android.location.LocationManager;
import android.media.AudioManager;
import android.media.Ringtone;
import android.media.RingtoneManager;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.Uri;
import android.net.wifi.WifiManager;
import android.os.BatteryManager;
import android.os.Build;
import android.os.Environment;
import android.os.Handler;
import android.os.PowerManager;
import android.os.StatFs;
import android.os.VibrationEffect;
import android.os.Vibrator;
import android.provider.CalendarContract;
import android.provider.CallLog;
import android.provider.ContactsContract;
import android.provider.Settings;
import android.telephony.TelephonyManager;
import android.util.Log;
import android.view.Surface;
import android.view.WindowManager;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.RelativeLayout;

import androidx.annotation.NonNull;
import androidx.annotation.RequiresApi;
import androidx.appcompat.app.AppCompatDelegate;


import com.feilong.edgeAI.model.RingListBean;
import com.hjq.toast.Toaster;

import java.io.DataOutputStream;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.lang.reflect.Method;
import java.math.BigDecimal;
import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
import java.util.concurrent.atomic.AtomicReference;

public class EdgeManager {

    @SuppressLint("StaticFieldLeak")
    private static EdgeManager edgeManager;
    protected Context mContext;


    private EdgeManager() {
    }

    public static synchronized EdgeManager getInstance() {
        if (edgeManager == null)
            edgeManager = new EdgeManager();
        return edgeManager;
    }


    public void setContext(Context context) {
        if (context == null) {
            Log.e("context ", "设置为空");
        }

        this.mContext = context;
    }


    /**
     * 设备重启
     */
    @SuppressLint("MissingPermission")
    public void reboot() {

        if (this.mContext == null) {
            Log.e("上下文为空，不执行", "请检查是否已调用setContext()");
        } else {
            // 执行重启操作
            PowerManager pm = (PowerManager) mContext.getSystemService(Context.POWER_SERVICE);
            if (pm != null) {
                pm.reboot(null);
            }
        }

    }

    /**
     * 设备关机
     */
    public void shutdown() {

    }


    /**
     * 打开蓝牙
     */
    public void openBluetooth() {

        if (this.mContext == null) {
            Log.e("上下文为空，不执行", "请检查是否已调用setContext()");
        } else {
            BluetoothAdapter bluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
            bluetoothAdapter.enable();  //使用常规方式打开蓝牙
        }

    }

    /**
     * 关闭蓝牙
     */
    public void closeBluetooth() {

        if (this.mContext == null) {
            Log.e("上下文为空，不执行", "请检查是否已调用setContext()");
        } else {
            BluetoothAdapter bluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
            bluetoothAdapter.disable();  //使用常规方式打开蓝牙
        }

    }


    /**
     * 蓝牙状态
     *
     * @return true 蓝牙已打开状态  蓝牙关闭状态
     */
    public boolean getBluetoothState() {

        if (this.mContext == null) {
            Log.e("上下文为空，不执行", "请检查是否已调用setContext()");
        } else {
            BluetoothAdapter bluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
            return bluetoothAdapter.isEnabled();  //判断蓝牙是否打开
        }
        return false;
    }

    private static final String TAG = "edgemanager";
    /**
     * 调节亮度
     *
     * @param brightnessValue 0-255
     */
    public void setScreenBrightness(int brightnessValue) {
        Log.d("edgemanager", "getScreenBrightness: "+getScreenBrightness());
        Log.d("edgemanager", "setScreenBrightness: "+brightnessValue);
        if (this.mContext == null) {
            Log.e("上下文为空，不执行", "请检查是否已调用setContext()");
        } else {
            // 设置亮度值（0-255）
            Settings.System.putInt(mContext.getContentResolver(), Settings.System.SCREEN_BRIGHTNESS, brightnessValue);

            if (mContext instanceof Activity) {
                // 通知系统亮度值已更改
                WindowManager.LayoutParams layoutParams = ((Activity) mContext).getWindow().getAttributes();
                layoutParams.screenBrightness = brightnessValue / 255f;
                Log.d(TAG, "setScreenBrightness: "+layoutParams.screenBrightness);
                ((Activity) mContext).getWindow().setAttributes(layoutParams);
            }
        }

    }

    public void inScreenBrightness() {
        int brightnessValue = getScreenBrightness()+25;
        if (this.mContext == null) {
            Log.e("上下文为空，不执行", "请检查是否已调用setContext()");
        } else {
            // 设置亮度值（0-255）
            Settings.System.putInt(mContext.getContentResolver(), Settings.System.SCREEN_BRIGHTNESS, brightnessValue);

            if (mContext instanceof Activity) {
                // 通知系统亮度值已更改
                WindowManager.LayoutParams layoutParams = ((Activity) mContext).getWindow().getAttributes();
                layoutParams.screenBrightness = brightnessValue / 255f;
                ((Activity) mContext).getWindow().setAttributes(layoutParams);
            }
        }

    }

    public void deScreenBrightness() {
        int brightnessValue = getScreenBrightness()-25;
        if(brightnessValue<0){
            brightnessValue=0;
        }
        if (this.mContext == null) {
            Log.e("上下文为空，不执行", "请检查是否已调用setContext()");
        } else {
            // 设置亮度值（0-255）
            Settings.System.putInt(mContext.getContentResolver(), Settings.System.SCREEN_BRIGHTNESS, brightnessValue);

            if (mContext instanceof Activity) {
                // 通知系统亮度值已更改
                WindowManager.LayoutParams layoutParams = ((Activity) mContext).getWindow().getAttributes();
                layoutParams.screenBrightness = brightnessValue / 255f;
                ((Activity) mContext).getWindow().setAttributes(layoutParams);
            }
        }

    }


    /**
     * 获取当前屏幕亮度值
     *
     * @return
     */
    public int getScreenBrightness() {
        if (this.mContext == null) {
            Log.e("上下文为空，不执行", "请检查是否已调用setContext()");
        } else {
            int currentBrightness;
            try {
                currentBrightness = Settings.System.getInt(mContext.getContentResolver(), Settings.System.SCREEN_BRIGHTNESS);
                Log.d("edgemanager", "getScreenBrightness: "+currentBrightness);
                return currentBrightness;
            } catch (Settings.SettingNotFoundException e) {
                e.printStackTrace();
            }
        }
        return -1;
    }


    /**
     * 移动网络开关
     *
     * @param isopen true 打开  false 关闭
     */
    public void mobileNetwork(boolean isopen) {

        if (this.mContext == null) {
            Log.e("上下文为空，不执行", "请检查是否已调用setContext()");
        } else {
            ConnectivityManager connectivityManager = (ConnectivityManager) mContext.getSystemService(Context.CONNECTIVITY_SERVICE);
            if (connectivityManager != null) {
                Method setMobileDataEnabledMethod;
                try {
                    setMobileDataEnabledMethod = ConnectivityManager.class.getDeclaredMethod("setDataEnabled", boolean.class);
                    setMobileDataEnabledMethod.invoke(connectivityManager, isopen);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }

    }
    /**
     * 无线网络开关
     *
     * @param isopen true 打开  false 关闭
     */
    public void wifiNetwork(boolean isopen) {
        WifiManager wifiManager = (WifiManager) mContext.getSystemService(Context.WIFI_SERVICE);
        wifiManager.setWifiEnabled(isopen);
    }


    /**
     * 移动网络状态
     *
     * @return true  移动网络打开   false
     */
    public boolean getMobileNetworkState() {

        if (this.mContext == null) {
            Log.e("上下文为空，不执行", "请检查是否已调用setContext()");
        } else {
            ConnectivityManager connectivityManager = (ConnectivityManager) mContext.getSystemService(Context.CONNECTIVITY_SERVICE);
            if (connectivityManager != null) {
                NetworkInfo mobileNetworkInfo = connectivityManager.getNetworkInfo(ConnectivityManager.TYPE_MOBILE);
                if (mobileNetworkInfo != null) {
                    boolean isMobileConnected = mobileNetworkInfo.isConnected();
                    boolean isMobileAvailable = mobileNetworkInfo.isAvailable();

                    return isMobileConnected;
                }
            }
        }
        return false;
    }

    /**
     * 判断是否有SIM卡
     *
     * @return 有SIM卡返回true，没有返回false。
     */
    public boolean isHaveSIMCard() {
        if (this.mContext == null) {
            Log.e("上下文为空，不执行", "请检查是否已调用setContext()");
        } else {
            TelephonyManager tm = (TelephonyManager) mContext.getSystemService(mContext.TELEPHONY_SERVICE);
            return tm.getSimState() == TelephonyManager.SIM_STATE_READY;
        }
        return false;
    }


    private WifiManager.LocalOnlyHotspotReservation currentReservation;


    /**
     * 打开热点
     */
    @RequiresApi(api = Build.VERSION_CODES.O)
    public void openHotspot() {

        if (this.mContext == null) {
            Log.e("上下文为空，不执行", "请检查是否已调用setContext()");
        } else {
            WifiManager wifiManager = (WifiManager) mContext.getSystemService(Context.WIFI_SERVICE);
            if (wifiManager != null) {

                if (currentReservation != null) {
                    closePreviousHotspot(currentReservation);  // 先关闭之前的请求
                }

                wifiManager.startLocalOnlyHotspot(new WifiManager.LocalOnlyHotspotCallback() {
                    @Override
                    public void onStarted(WifiManager.LocalOnlyHotspotReservation reservation) {
                        super.onStarted(reservation);
                        currentReservation = reservation;
                        if (reservation != null) {
                            // 热点已成功打开
//                            Toaster.showShort("热点已成功打开");
                        } else {
                            // 无法打开热点
//                            Toaster.showShort("无法打开热点");
                        }

                    }

                    @Override
                    public void onFailed(int reason) {
                        super.onFailed(reason);
                        // 无法打开热点
//                        Toaster.showShort("无法打开热点");
                    }
                }, new Handler());
            }
        }

    }

    /**
     * 关闭热点
     */
    @RequiresApi(api = Build.VERSION_CODES.O)
    public void closeHotspot() {

        if (this.mContext == null) {
            Log.e("上下文为空，不执行", "请检查是否已调用setContext()");
        } else {
            WifiManager wifiManager = (WifiManager) mContext.getSystemService(Context.WIFI_SERVICE);
            if (wifiManager != null) {

                if (currentReservation != null) {
                    closePreviousHotspot(currentReservation);
                    return;
                }


                wifiManager.startLocalOnlyHotspot(new WifiManager.LocalOnlyHotspotCallback() {
                    @Override
                    public void onStarted(WifiManager.LocalOnlyHotspotReservation reservation) {
                        super.onStarted(reservation);

                        if (reservation != null) {
                            // 关闭之前的 LocalOnlyHotspot 请求
                            closePreviousHotspot(reservation);
                        }

                    }

                    @Override
                    public void onStopped() {
                        super.onStopped();
//                        Toaster.showShort("热点已关闭");
                    }

                    @Override
                    public void onFailed(int reason) {
                        super.onFailed(reason);
                        // 无法关闭热点
//                        Toaster.showShort("无法关闭热点");
                    }
                }, new Handler());
            }
        }

    }

    // 关闭之前的 LocalOnlyHotspot 请求
    private void closePreviousHotspot(WifiManager.LocalOnlyHotspotReservation currentReservation) {
        if (currentReservation != null) {
            currentReservation.close();
            this.currentReservation = null;
//            Toaster.showShort("热点关闭成功");
        }
    }


    /**
     * 获取热点的状态
     */
    public boolean getHotspotState() {
        //目前没找到接口

        return false;
    }


    /**
     * 打开自动亮度
     *
     * @return true  成功 false 失败
     */
    public boolean openAutomaticBrightness() {
        if (this.mContext == null) {
            Log.e("上下文为空，不执行", "请检查是否已调用setContext()");
        } else {
            // 打开自动屏幕亮度调节
            return Settings.System.putInt(
                    mContext.getContentResolver(),
                    Settings.System.SCREEN_BRIGHTNESS_MODE,
                    Settings.System.SCREEN_BRIGHTNESS_MODE_AUTOMATIC
            );

        }

        return false;

    }

    /**
     * 关闭自动亮度
     */
    public boolean closeAutomaticBrightness() {

        if (this.mContext == null) {
            Log.e("上下文为空，不执行", "请检查是否已调用setContext()");
        } else {
            // 打开自动屏幕亮度调节
            return Settings.System.putInt(
                    mContext.getContentResolver(),
                    Settings.System.SCREEN_BRIGHTNESS_MODE,
                    Settings.System.SCREEN_BRIGHTNESS_MODE_MANUAL
            );
        }
        return false;
    }


    /**
     * 获取是否打开自动亮度
     *
     * @return true 打开自动亮度调节 false 关闭自动亮度调节
     */
    public boolean getAutomaticBrightnessState() {
        //目前没找到接口
        if (this.mContext == null) {
            Log.e("上下文为空，不执行", "请检查是否已调用setContext()");
        } else {
            int mode = Settings.System.getInt(mContext.getContentResolver(), Settings.System.SCREEN_BRIGHTNESS_MODE, Settings.System.SCREEN_BRIGHTNESS_MODE_MANUAL);
            if (mode == Settings.System.SCREEN_BRIGHTNESS_MODE_AUTOMATIC) {
                return true;
            } else if (mode == Settings.System.SCREEN_BRIGHTNESS_MODE_MANUAL) {
                return false;
            }

        }
        return false;
    }


    /**
     * 打开和关闭手电筒
     *
     * @param isOpen true 打开 open关闭
     */
    @RequiresApi(api = Build.VERSION_CODES.M)
    public void flashlightSwitch(boolean isOpen) {
        if (this.mContext == null) {
            Log.e("上下文为空，不执行", "请检查是否已调用setContext()");
        } else {
            CameraManager cameraManager = (CameraManager) mContext.getSystemService(CAMERA_SERVICE);
            try {
                String cameraId = getCameraId(cameraManager); // 获取相机ID
                if (cameraId != null) {
                    cameraManager.setTorchMode(cameraId, isOpen);
                }
            } catch (CameraAccessException e) {
                e.printStackTrace();
            }
        }

    }

    // 获取相机ID
    private String getCameraId(CameraManager cameraManager) throws CameraAccessException {
        String[] cameraIds = cameraManager.getCameraIdList();
        for (String id : cameraIds) {
            boolean hasFlash = Boolean.TRUE.equals(cameraManager.getCameraCharacteristics(id)
                    .get(CameraCharacteristics.FLASH_INFO_AVAILABLE));
            if (hasFlash) {
                return id;
            }
        }
        return null;
    }

    /**
     * 获取手电筒当前状态
     */
    @RequiresApi(api = Build.VERSION_CODES.M)
    public void getFlashlightState() {
        //目前没找到接口
        if (this.mContext == null) {
            Log.e("上下文为空，不执行", "请检查是否已调用setContext()");
        } else {
            CameraManager cameraManager = (CameraManager) mContext.getSystemService(CAMERA_SERVICE);
            CameraManager.TorchCallback torchCallback = new CameraManager.TorchCallback() {
                @Override
                public void onTorchModeChanged(@NonNull String cameraId, boolean enabled) {
//                    Toaster.showShort(enabled ? "手电筒已打开" : "手电筒已关闭");

                }
            };
            cameraManager.registerTorchCallback(torchCallback, null);

        }
    }


    /**
     * 打开和关闭飞行模式
     *
     * @param isOpen true 打开 open关闭
     * @return true 设置成功  设置失败
     */
    public boolean airplaneModeSwitch(boolean isOpen) {
        if (this.mContext == null) {
            Log.e("上下文为空，不执行", "请检查是否已调用setContext()");
        } else {
            // 获取系统服务
            ContentResolver contentResolver = mContext.getContentResolver();
            // 打开飞行模式
            boolean putInt = Settings.Global.putInt(contentResolver, Settings.Global.AIRPLANE_MODE_ON, isOpen ? 1 : 0);
            // 发送广播通知系统飞行模式已经改变
            Intent intent = new Intent(Intent.ACTION_AIRPLANE_MODE_CHANGED);
            intent.putExtra("state", isOpen);
            mContext.sendBroadcast(intent);

            return putInt;
        }

        return false;

    }


    /**
     * 获取飞行模式当前状态
     *
     * @return true  手电筒打开  flase 手电筒关闭
     */
    public boolean getAirplaneModeState() {
        //目前没找到接口
        if (this.mContext == null) {
            Log.e("上下文为空，不执行", "请检查是否已调用setContext()");
        } else {
            // 获取系统服务
            ContentResolver contentResolver = mContext.getContentResolver();
            // 获取飞行模式的状态
            return Settings.Global.getInt(contentResolver, Settings.Global.AIRPLANE_MODE_ON, 0) != 0;
        }
        return false;
    }


    /**
     * 获取定位当前状态
     *
     * @return true 定位打开状态  false 定位关闭状态
     */
    public boolean getLocationState() {
        //目前没找到接口
        if (this.mContext == null) {
            Log.e("上下文为空，不执行", "请检查是否已调用setContext()");
        } else {
            // 获取系统服务
            LocationManager locationManager = (LocationManager) mContext.getSystemService(Context.LOCATION_SERVICE);
            // 检查定位是否已经开启
            return locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER);
        }
        return false;
    }


    /**
     * 打开护眼模式/关闭护眼模式
     *
     * @param isOpen true 打开 open关闭
     */
    public boolean eyeProtectionModeSwitch(boolean isOpen) {
        if (this.mContext == null) {
            Log.e("上下文为空，不执行", "请检查是否已调用setContext()");
        } else {
            // 获取系统服务
            ContentResolver contentResolver = mContext.getContentResolver();

            // 检查护眼模式是否已经开启
            int currentMode = Settings.System.getInt(contentResolver, Settings.System.SCREEN_BRIGHTNESS_MODE, Settings.System.SCREEN_BRIGHTNESS_MODE_MANUAL);
            boolean isEyeProtectionEnabled = (currentMode == Settings.System.SCREEN_BRIGHTNESS_MODE_AUTOMATIC);
            if (isOpen) {
                // 打开护眼模式
                if (!isEyeProtectionEnabled) {
                    Settings.System.putInt(contentResolver, Settings.System.SCREEN_BRIGHTNESS_MODE, Settings.System.SCREEN_BRIGHTNESS_MODE_AUTOMATIC);
                }
            } else {
                // 关闭护眼模式
                if (isEyeProtectionEnabled) {
                    Settings.System.putInt(contentResolver, Settings.System.SCREEN_BRIGHTNESS_MODE, Settings.System.SCREEN_BRIGHTNESS_MODE_MANUAL);
                }
            }

            // 再次检查护眼模式是否已经开启
            currentMode = Settings.System.getInt(contentResolver, Settings.System.SCREEN_BRIGHTNESS_MODE, Settings.System.SCREEN_BRIGHTNESS_MODE_MANUAL);
            isEyeProtectionEnabled = (currentMode == Settings.System.SCREEN_BRIGHTNESS_MODE_AUTOMATIC);
            return isOpen == isEyeProtectionEnabled;
        }

        return false;
    }


    /**
     * 护眼模式 状态
     *
     * @return true 打开 open关闭
     */
    public boolean getEyeProtectionModeState() {
        if (this.mContext == null) {
            Log.e("上下文为空，不执行", "请检查是否已调用setContext()");
        } else {
            // 获取系统服务
            ContentResolver contentResolver = mContext.getContentResolver();
            // 检查护眼模式是否已经开启
            int currentMode = Settings.System.getInt(contentResolver, Settings.System.SCREEN_BRIGHTNESS_MODE, Settings.System.SCREEN_BRIGHTNESS_MODE_MANUAL);
            return (currentMode == Settings.System.SCREEN_BRIGHTNESS_MODE_AUTOMATIC);
        }

        return false;
    }


    /**
     * 打开深色模式/关闭深色模式
     *
     * @param isOpen isOpen true 打开 open关闭
     * @return true 设置成功  false 设置失败
     */
    public boolean darkModeSwitch(boolean isOpen) {
        if (this.mContext == null) {
            Log.e("上下文为空，不执行", "请检查是否已调用setContext()");
        } else {
            // 获取当前模式
            int currentNightMode = mContext.getResources().getConfiguration().uiMode & Configuration.UI_MODE_NIGHT_MASK;
            // 检查是否已经开启夜间模式
            boolean isNightModeEnabled = currentNightMode == Configuration.UI_MODE_NIGHT_YES;
            if (isOpen) {

                if (!isNightModeEnabled) {
                    // 打开夜间模式
                    AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE_NIGHT_YES);
                }
            } else {
                if (isNightModeEnabled) {
                    // 关闭夜间模式
                    AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE_NIGHT_NO);
                }
            }

            // 再次检查夜间模式是否已经开启
            currentNightMode = mContext.getResources().getConfiguration().uiMode & Configuration.UI_MODE_NIGHT_MASK;
            isNightModeEnabled = currentNightMode == Configuration.UI_MODE_NIGHT_YES;
            return isOpen == isNightModeEnabled;
        }

        return false;
    }

    /**
     * 深色模式状态
     *
     * @return true 深色模式打开状态 open深色模式关闭状态
     */
    public boolean getDarkModeState() {
        if (this.mContext == null) {
            Log.e("上下文为空，不执行", "请检查是否已调用setContext()");
        } else {
            // 获取当前模式
            int currentNightMode = mContext.getResources().getConfiguration().uiMode & Configuration.UI_MODE_NIGHT_MASK;
            // 检查是否已经开启夜间模式
            return currentNightMode == Configuration.UI_MODE_NIGHT_YES;
        }

        return false;
    }


    int _execCmdAsSU(String strSU, String cmd) throws Exception {
        Process p = Runtime.getRuntime().exec(strSU);
        DataOutputStream dos = new DataOutputStream(p.getOutputStream());
        dos.writeBytes(cmd + "\n");
        dos.flush();
        dos.writeBytes("exit\n");
        dos.flush();
        int result = p.waitFor();
        dos.close();
        return result;
    }

    /**
     * 打开省电模式/关闭省电模式
     *
     * @return true 设置成功  false 设置失败
     */
    public void openPowerSavingMode() {
        if (this.mContext == null) {
            Log.e("上下文为空，不执行", "请检查是否已调用setContext()");
        } else {

        }

    }

    /**
     * 省电模式的状态
     *
     * @return true 打开省电模式  false 关闭省电状态
     */
    public boolean getPowerSavingModeState() {
        if (this.mContext == null) {
            Log.e("上下文为空，不执行", "请检查是否已调用setContext()");
        } else {
            PowerManager powerManager = (PowerManager) mContext.getSystemService(Context.POWER_SERVICE);
            if (powerManager != null) {
                return powerManager.isPowerSaveMode();
            }

            return false;

        }
        return false;
    }


    /**
     * 打开静音
     *
     * @return true 打开静音成功  false 打开静音失败
     */
    public boolean openMute() {
        if (this.mContext == null) {
            Log.e("上下文为空，不执行", "请检查是否已调用setContext()");
        } else {
            AudioManager audioManager = (AudioManager) mContext.getSystemService(Context.AUDIO_SERVICE);
            audioManager.setRingerMode(AudioManager.RINGER_MODE_SILENT);
            int ringerMode = audioManager.getRingerMode();
            // 当前为静音模式
            return ringerMode == AudioManager.RINGER_MODE_SILENT;

        }
        return false;
    }


    /**
     * 关闭静音
     *
     * @return true 关闭静音成功  false 关闭静音失败
     */
    public boolean closeMute() {
        if (this.mContext == null) {
            Log.e("上下文为空，不执行", "请检查是否已调用setContext()");
        } else {
            AudioManager audioManager = (AudioManager) mContext.getSystemService(Context.AUDIO_SERVICE);
            audioManager.setRingerMode(AudioManager.RINGER_MODE_NORMAL);
            int ringerMode = audioManager.getRingerMode();

            return ringerMode != AudioManager.RINGER_MODE_SILENT;//不是静音模式

        }
        return false;
    }


    /**
     * 获取静音当前状态
     *
     * @return 1 当前为静音模式  2 当前为震动模式  3 当前为普通模式  0是获取当前模式失败
     */
    public int getMuteState() {
        if (this.mContext == null) {
            Log.e("上下文为空，不执行", "请检查是否已调用setContext()");
        } else {
            AudioManager audioManager = (AudioManager) mContext.getSystemService(Context.AUDIO_SERVICE);
            int ringerMode = audioManager.getRingerMode();

            if (ringerMode == AudioManager.RINGER_MODE_SILENT) {
                // 当前为静音模式
                return 1;
            } else if (ringerMode == AudioManager.RINGER_MODE_VIBRATE) {
                // 当前为震动模式
                return 2;
            } else {
                // 当前为普通模式
                return 3;
            }
        }
        return 0;
    }


    /**
     * 设置声音模式
     *
     * @param mode 0是音效模式  1是静音模式  2是震动模式
     * @return true 设置成功  false 设置失败
     */
    public boolean setSoundMode(int mode) {
        if (this.mContext == null) {
            Log.e("上下文为空，不执行", "请检查是否已调用setContext()");
        } else {
            // 获取AudioManager对象
            AudioManager audioManager = (AudioManager) mContext.getSystemService(Context.AUDIO_SERVICE);
            if (mode == 0) {
                // 设置音量模式为音效模式
                audioManager.setRingerMode(AudioManager.RINGER_MODE_NORMAL);
            } else if (mode == 1) {
                // 设置音量模式为静音模式
                audioManager.setRingerMode(AudioManager.RINGER_MODE_SILENT);
            } else if (mode == 2) {
                // 设置音量模式为振动模式
                audioManager.setRingerMode(AudioManager.RINGER_MODE_VIBRATE);
            }
            // 获取当前音量模式
            int ringerMode = audioManager.getRingerMode();
            if (mode == 0) {
                return ringerMode == AudioManager.RINGER_MODE_NORMAL;//当前处于音效模式
            } else if (mode == 1) {
                return ringerMode == AudioManager.RINGER_MODE_SILENT;//当前处于静音模式
            } else if (mode == 2) {
                return ringerMode == AudioManager.RINGER_MODE_VIBRATE;//当前处于振动模式
            }


        }
        return false;
    }


    /**
     * 响铃时震动／铃声选择／通知音效／系统音效
     *
     * @return 0 响铃时震动  1 铃声选择  2 通知音效  3系统音效
     */
    public void setringingBellMode(int mode) {
        if (this.mContext == null) {
            Log.e("上下文为空，不执行", "请检查是否已调用setContext()");
        } else {
            // 获取AudioManager对象
            AudioManager audioManager = (AudioManager) mContext.getSystemService(Context.AUDIO_SERVICE);

            if (mode == 0) {
                // 设置响铃模式为震动模式
                audioManager.setRingerMode(AudioManager.RINGER_MODE_VIBRATE);
            } else if (mode == 1) {
                // 设置铃声
                audioManager.setStreamVolume(AudioManager.STREAM_RING, audioManager.getStreamMaxVolume(AudioManager.STREAM_RING), 0);

            } else if (mode == 2) {
                // 设置通知音效
                audioManager.setStreamVolume(AudioManager.STREAM_NOTIFICATION, audioManager.getStreamMaxVolume(AudioManager.STREAM_NOTIFICATION), 0);
            } else if (mode == 3) {
                // 设置系统音效
                audioManager.setStreamVolume(AudioManager.STREAM_SYSTEM, audioManager.getStreamMaxVolume(AudioManager.STREAM_SYSTEM), 0);
            }
        }

    }


    /**
     * 获取声音模式
     *
     * @return 0是音效模式  1是静音模式  2是震动模式
     */
    public int getSoundState() {
        if (this.mContext == null) {
            Log.e("上下文为空，不执行", "请检查是否已调用setContext()");
        } else {
            AudioManager audioManager = (AudioManager) mContext.getSystemService(Context.AUDIO_SERVICE);

            // 获取当前音量模式
            int ringerMode = audioManager.getRingerMode();
            if (ringerMode == AudioManager.RINGER_MODE_SILENT) {
                // 当前处于静音模式
                return 1;
            } else if (ringerMode == AudioManager.RINGER_MODE_VIBRATE) {
                // 当前处于振动模式
                return 2;
            } else if (ringerMode == AudioManager.RINGER_MODE_NORMAL) {
                // 当前处于音效模式
                return 0;
            }
        }
        return 0;
    }

    /**
     * 设置震动强度
     *
     * @return amplitude 设置震动强度（范围：1-255）
     */
    @RequiresApi(api = Build.VERSION_CODES.O)
    public void setVibrationIntensity(int amplitude) {
        if (this.mContext == null) {
            Log.e("上下文为空，不执行", "请检查是否已调用setContext()");
        } else {
            // 获取系统震动服务
            Vibrator vibrator = (Vibrator) mContext.getSystemService(Context.VIBRATOR_SERVICE);
            // 检查设备是否支持调整震动强度
            if (vibrator.hasAmplitudeControl()) {
                //
                VibrationEffect vibrationEffect = VibrationEffect.createOneShot(1000, amplitude);
                vibrator.vibrate(vibrationEffect);
            } else {
                // 设备不支持调整震动强度
                Toaster.showShort("设备不支持震动强度调整");
            }
        }
    }


    /**
     * 设置铃声
     *
     * @param type RingtoneManager.TYPE_RINGTONE 来电铃声    RingtoneManager.TYPE_NOTIFICATION 通知铃声  RingtoneManager.TYPE_ALL 系统铃声
     */
    public void setRing(int type) {

        AtomicReference<Ringtone> ringtone = new AtomicReference<>();
        AtomicReference<Uri> ringtoneUri = new AtomicReference<>();
        if (this.mContext == null) {
            Log.e("上下文为空，不执行", "请检查是否已调用setContext()");
        } else {
            // 获取系统的铃声管理器
            RingtoneManager ringtoneManager = new RingtoneManager(mContext);
            List<RingListBean> ringList = getRingList(ringtoneManager, type);
            List<String> stringsList = new ArrayList<>();

            for (int i = 0; i < ringList.size(); i++) {
                RingListBean ringListBean = ringList.get(i);
                String title = ringListBean.getTitle();
                stringsList.add(title);

            }

            // 创建构建器对象并设置标题和列表项
            AlertDialog.Builder builder = new AlertDialog.Builder(mContext);
            builder.setTitle("选择铃声");

            // 创建列表适配器
            ArrayAdapter<String> adapter = new ArrayAdapter<>(mContext, android.R.layout.simple_list_item_1, stringsList);
            // 设置列表项点击事件
            builder.setAdapter(adapter, (dialog, which) -> {
            });

            builder.setCancelable(false);
            builder.setPositiveButton("确定", (dialogInterface, i) -> {
                Uri uri = ringtoneUri.get();
                if (uri == null) {
                    Toaster.showShort("选择要设置铃声");
                    return;
                }
                Ringtone ringtone1 = ringtone.get();
                if (ringtone1 != null && ringtone1.isPlaying()) {
                    ringtone1.stop();//暂停播放
                }
                RingtoneManager.setActualDefaultRingtoneUri(mContext, type, uri);
                // 设置所选的铃声为来电铃声
                dialogInterface.dismiss();
            });
            builder.setNegativeButton("取消", (dialogInterface, i) -> {
                // 设置所选的铃声为来电铃声
                dialogInterface.dismiss();
                Ringtone ringtone1 = ringtone.get();
                if (ringtone1 != null && ringtone1.isPlaying()) {
                    ringtone1.stop();
                }
            });
            // 显示对话框
            AlertDialog dialog = builder.create();
            dialog.show();
            // 获取ListView并设置点击事件
            ListView listView = dialog.getListView();
            listView.setOnItemClickListener((parent, view, position, id) -> {
                //列表点击
                Ringtone ringtone1 = ringtone.get();
                if (ringtone1 != null && ringtone1.isPlaying()) {
                    ringtone1.stop();//如果上次有播放 先暂停
                }
                // 在此处添加点击列表项的逻辑
                RingListBean ringListBean = ringList.get(position);
                ringtoneUri.set(ringListBean.getRingtoneUri());
                // 设置来电铃声
                ringtone.set(RingtoneManager.getRingtone(mContext, ringtoneUri.get()));
                ringtone.get().play();

            });
        }

    }

    /**
     * 获取铃声列表
     */
    public List<RingListBean> getRingList(RingtoneManager ringtoneManager, int type) {

        List<RingListBean> ringListBeanList = new ArrayList<>();

        if (this.mContext == null) {
            Log.e("上下文为空，不执行", "请检查是否已调用setContext()");
        } else {

            // 设置铃声类型为来电铃声
            ringtoneManager.setType(type);
            // 获取铃声列表
            Cursor cursor = ringtoneManager.getCursor();
            int count = cursor.getCount();
            // 遍历铃声列表
            while (cursor.moveToNext()) {
                // 获取铃声标题和URI
                String title = cursor.getString(RingtoneManager.TITLE_COLUMN_INDEX);
                Uri ringtoneUri = ringtoneManager.getRingtoneUri(cursor.getPosition());
                RingListBean ringListBean = new RingListBean();
                ringListBean.setTitle(title);
                ringListBean.setRingtoneUri(ringtoneUri);
                ringListBeanList.add(ringListBean);
            }
            // 关闭游标
            cursor.close();

        }

        return ringListBeanList;
    }


    /**
     * 获取当前铃声
     *
     * @return 铃声名称
     */

    public String getCurrentRing(int type) {
        if (this.mContext == null) {
            Log.e("上下文为空，不执行", "请检查是否已调用setContext()");
        } else {
            // 获取系统设置的来电铃声URI
            Uri ringtoneUri = RingtoneManager.getActualDefaultRingtoneUri(mContext, type);
            // 将来电铃声URI转换为Ringtone对象
            Ringtone ringtone = RingtoneManager.getRingtone(mContext, ringtoneUri);
            // 获取来电铃声的名称
            return ringtone.getTitle(mContext);

        }
        return "";
    }


    /**
     * 设置屏幕方向
     *
     * @param type 1打开方向锁定  2关闭方向锁定   3横向模式   4纵向模式   5自动方向
     */
    public void setScreenOrientationSet(int type) {
        if (this.mContext == null) {
            Log.e("上下文为空，不执行", "请检查是否已调用setContext()");
        } else {

            if (mContext instanceof Activity) {

                Activity activity = (Activity) mContext;
                if (type == 1) {
                    // 获取当前屏幕方向
                    int orientation = activity.getResources().getConfiguration().orientation;
                    // 锁定屏幕方向
                    activity.setRequestedOrientation(orientation);
                } else if (type == 2) {
                    // 解除屏幕方向锁定
                    activity.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_UNSPECIFIED);
                } else if (type == 3) {
                    // 设置横向模式
                    activity.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
                } else if (type == 4) {
                    // 设置纵向模式
                    activity.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
                } else if (type == 5) {
                    // 设置自动方向
                    activity.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_SENSOR);
                }
            }
        }
    }


    /**
     * @return 1 竖屏 2 横屏向左  3倒置 4 横屏向右  0未知
     */
    public int getScreenOrientation() {
        if (this.mContext == null) {
            Log.e("上下文为空，不执行", "请检查是否已调用setContext()");
        } else {

            if (mContext instanceof Activity) {
                int rotation = ((Activity) mContext).getWindowManager().getDefaultDisplay().getRotation();
                String orientation;
                switch (rotation) {
                    case Surface.ROTATION_0:
                        orientation = "竖屏";
                        return 1;
                    case Surface.ROTATION_90:
                        orientation = "横屏向左";
                        return 2;
                    case Surface.ROTATION_180:
                        orientation = "倒置";
                        return 3;
                    case Surface.ROTATION_270:
                        orientation = "横屏向右";
                        return 4;
                    default:
                        orientation = "未知";
                        return 0;
                }
            }
        }
        return 0;
    }

    boolean mIsRecording;
    Process process;
    String videoFilePath;

    /**
     * 启动录屏
     */
    public void startRecord() {
        if (this.mContext == null) {
            Log.e("上下文为空，不执行", "请检查是否已调用setContext()");
        } else {

            try {
                // 创建保存视频文件的路径
                videoFilePath = Objects.requireNonNull(mContext.getExternalFilesDir(null)).getAbsolutePath() + "/" + System.currentTimeMillis() + ".mp4";
                // 录制命令
                String[] recordCommand = {"screenrecord", "--size", "720x1280", "--bit-rate", "5000000", videoFilePath};
                // 执行录制命令
                process = Runtime.getRuntime().exec(recordCommand);
                // 标记正在录制
                mIsRecording = true;
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }


    @RequiresApi(api = Build.VERSION_CODES.O)
    public void stopRecord() {
        if (this.mContext == null) {
            Log.e("上下文为空，不执行", "请检查是否已调用setContext()");
        } else {
            if (process != null) {
                process.destroyForcibly();
                try {
                    // 等待录制进程完成
                    int exitCode = process.waitFor();
                    if (exitCode == 0) {
                        // 录制进程正常退出
                        // 在录制完成后可以处理录制的视频文件，例如分享、保存等操作
                        // 这里只是简单地显示文件路径
                        Toaster.showShort("录制完成：" + videoFilePath);
                    } else {
                        // 录制进程异常退出
                        // 可以根据具体情况进行处理
                        Toaster.showShort("录制异常退出，退出码：" + exitCode);
                    }
                } catch (InterruptedException e) {
                    e.printStackTrace();
                    // 处理异常情况，例如显示错误消息或进行其他操作
                }
                process = null;
            }
        }
    }


    /**
     * 截屏
     */
    public void screenshot() {
        if (this.mContext == null) {
            Log.e("上下文为空，不执行", "请检查是否已调用setContext()");
        } else {

            try {
                String command = "/system/bin/screencap -p /sdcard/screenshot.png";
                Runtime.getRuntime().exec(command);

            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }


    /**
     * 字号调大一点
     */
    public void amplifyFontSizeAdjustmen() {
        if (this.mContext == null) {
            Log.e("上下文为空，不执行", "请检查是否已调用setContext()");
        } else {

            try {

                float aFloat = Settings.System.getFloat(mContext.getContentResolver(),
                        Settings.System.FONT_SCALE);
//系统要求字号大小的范围在 0.85 到 1.3 之间
                if (aFloat + 0.1f > 1.3f) {
                    Toaster.showShort("已是最大号字体");
                    return;
                }

                Settings.System.putFloat(mContext.getContentResolver(),
                        Settings.System.FONT_SCALE, aFloat + 0.1f);
            } catch (Settings.SettingNotFoundException e) {
                e.printStackTrace();
            }
        }
    }

    /**
     * 字号调小一点
     */
    public void reduceFontSizeAdjustment() {
        if (this.mContext == null) {
            Log.e("上下文为空，不执行", "请检查是否已调用setContext()");
        } else {

            try {
                float aFloat = Settings.System.getFloat(mContext.getContentResolver(),
                        Settings.System.FONT_SCALE);
                //系统要求字号大小的范围在 0.85 到 1.3 之间
                if (aFloat - 0.1f < 0.85f) {
                    Toaster.showShort("已是最小号字体");
                    return;
                }
                Settings.System.putFloat(mContext.getContentResolver(),
                        Settings.System.FONT_SCALE, aFloat - 0.1f);
            } catch (Settings.SettingNotFoundException e) {
                e.printStackTrace();
            }
        }
    }


    /**
     * 获取当前字号
     *
     * @return
     */
    public float getFontSizeAdjustment() {
        if (this.mContext == null) {
            Log.e("上下文为空，不执行", "请检查是否已调用setContext()");
        } else {

            try {

                return Settings.System.getFloat(mContext.getContentResolver(),
                        Settings.System.FONT_SCALE);
            } catch (Settings.SettingNotFoundException e) {
                e.printStackTrace();
            }
        }
        return -1;
    }

    /**
     * 备份通讯记录
     */
    public void backupCommunicationRecords() {
        if (this.mContext == null) {
            Log.e("上下文为空，不执行", "请检查是否已调用setContext()");
        } else {

            // 获取通话记录的 URI
            Uri callLogUri = CallLog.Calls.CONTENT_URI;
            // 查询通话记录数据
            Cursor cursor = mContext.getContentResolver().query(callLogUri, null, null, null, null);
            // 备份通话记录到文件
            File backupFile = new File(Environment.getExternalStorageDirectory(), "call_log_backup.txt");
            if (cursor != null && cursor.moveToFirst()) {
                StringBuilder callLogData = new StringBuilder();
                do {
                    @SuppressLint("Range") String number = cursor.getString(cursor.getColumnIndex(CallLog.Calls.NUMBER));
                    @SuppressLint("Range") String date = cursor.getString(cursor.getColumnIndex(CallLog.Calls.DATE));
                    @SuppressLint("Range") String duration = cursor.getString(cursor.getColumnIndex(CallLog.Calls.DURATION));

                    // 在此处可以将数据写入文件或进行其他处理
                    callLogData.append("Number: ").append(number)
                            .append(", Date: ").append(date)
                            .append(", Duration: ").append(duration)
                            .append("\n");
                } while (cursor.moveToNext());

                // 将通话记录数据写入备份文件
                try {
                    FileWriter writer = new FileWriter(backupFile);
                    writer.append(callLogData.toString());
                    writer.flush();
                    writer.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }

            // 关闭游标
            if (cursor != null) {
                cursor.close();
            }

        }
    }

    /**
     * 备份讯息
     */
    public void backupMessages() {
        if (this.mContext == null) {
            Log.e("上下文为空，不执行", "请检查是否已调用setContext()");
        } else {

            // 获取短信的 URI
            Uri smsUri = Uri.parse("content://sms");
            // 查询短信数据
            Cursor cursor = mContext.getContentResolver().query(smsUri, null, null, null, null);
            // 备份短信到文件
            File backupFile = new File(Environment.getExternalStorageDirectory(), "sms_backup.txt");
            if (cursor != null && cursor.moveToFirst()) {
                StringBuilder smsData = new StringBuilder();
                do {
                    @SuppressLint("Range") String address = cursor.getString(cursor.getColumnIndex("address"));
                    @SuppressLint("Range") String body = cursor.getString(cursor.getColumnIndex("body"));

                    // 在此处可以将数据写入文件或进行其他处理
                    smsData.append("Address: ").append(address)
                            .append(", Body: ").append(body)
                            .append("\n");
                } while (cursor.moveToNext());

                // 将短信数据写入备份文件
                try {
                    FileWriter writer = new FileWriter(backupFile);
                    writer.append(smsData.toString());
                    writer.flush();
                    writer.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }

            // 关闭游标
            if (cursor != null) {
                cursor.close();
            }


        }
    }


    /**
     * 备份联络人
     */
    public void backupContactPerson() {
        if (this.mContext == null) {
            Log.e("上下文为空，不执行", "请检查是否已调用setContext()");
        } else {

            // 获取联系人的 URI
            Uri contactsUri = ContactsContract.Contacts.CONTENT_URI;
            // 查询联系人数据
            Cursor cursor = mContext.getContentResolver().query(contactsUri, null, null, null, null);
            // 备份联系人到文件
            File backupFile = new File(Environment.getExternalStorageDirectory(), "contacts_backup.txt");
            if (cursor != null && cursor.moveToFirst()) {
                StringBuilder contactsData = new StringBuilder();
                do {
                    @SuppressLint("Range") String name = cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME));

                    // 在此处可以将数据写入文件或进行其他处理
                    contactsData.append("Name: ").append(name).append("\n");

                    // 获取联系人的电话号码
                    @SuppressLint("Range") String contactId = cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts._ID));
                    Cursor phoneCursor = mContext.getContentResolver().query(
                            ContactsContract.CommonDataKinds.Phone.CONTENT_URI,
                            null,
                            ContactsContract.CommonDataKinds.Phone.CONTACT_ID + " = ?",
                            new String[]{contactId},
                            null
                    );
                    if (phoneCursor != null && phoneCursor.moveToFirst()) {
                        do {
                            @SuppressLint("Range") String phoneNumber = phoneCursor.getString(phoneCursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));

                            // 在此处可以将数据写入文件或进行其他处理
                            contactsData.append("Phone: ").append(phoneNumber).append("\n");
                        } while (phoneCursor.moveToNext());

                        // 关闭电话游标
                        phoneCursor.close();
                    }
                } while (cursor.moveToNext());

                // 将联系人数据写入备份文件
                try {
                    FileWriter writer = new FileWriter(backupFile);
                    writer.append(contactsData.toString());
                    writer.flush();
                    writer.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }

            // 关闭游标
            if (cursor != null) {
                cursor.close();
            }
        }
    }


    /**
     * 备份日历
     */
    public void backupCalendar() {
        if (this.mContext == null) {
            Log.e("上下文为空，不执行", "请检查是否已调用setContext()");
        } else {

            // 获取日历事件的 URI
            Uri eventsUri = CalendarContract.Events.CONTENT_URI;
            // 查询日历事件数据
            Cursor cursor = mContext.getContentResolver().query(eventsUri, null, null, null, null);
            // 备份日历事件到文件
            File backupFile = new File(Environment.getExternalStorageDirectory(), "calendar_events_backup.txt");
            if (cursor != null && cursor.moveToFirst()) {
                StringBuilder eventsData = new StringBuilder();
                do {
                    @SuppressLint("Range") String title = cursor.getString(cursor.getColumnIndex(CalendarContract.Events.TITLE));
                    @SuppressLint("Range") String description = cursor.getString(cursor.getColumnIndex(CalendarContract.Events.DESCRIPTION));

                    // 在此处可以将数据写入文件或进行其他处理
                    eventsData.append("Title: ").append(title)
                            .append(", Description: ").append(description)
                            .append("\n");
                } while (cursor.moveToNext());

                // 将日历事件数据写入备份文件
                try {
                    FileWriter writer = new FileWriter(backupFile);
                    writer.append(eventsData.toString());
                    writer.flush();
                    writer.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }

// 关闭游标
            if (cursor != null) {
                cursor.close();
            }

        }
    }


    /**
     * 备份时钟
     */
    public void backupClock() {
        if (this.mContext == null) {
            Log.e("上下文为空，不执行", "请检查是否已调用setContext()");
        } else {

            // 获取闹钟的 URI
            Uri alarmUri = Uri.parse("content://com.android.deskclock/alarm");
            // 查询闹钟数据
            Cursor cursor = mContext.getContentResolver().query(alarmUri, null, null, null, null);
            // 备份闹钟到文件
            File backupFile = new File(Environment.getExternalStorageDirectory(), "alarm_backup.txt");
            if (cursor != null && cursor.moveToFirst()) {
                StringBuilder alarmData = new StringBuilder();
                do {
                    @SuppressLint("Range") String time = cursor.getString(cursor.getColumnIndex("alarmtime"));
                    // 在此处可以将数据写入文件或进行其他处理
                    alarmData.append("Time: ").append(time).append("\n");
                } while (cursor.moveToNext());

                // 将闹钟数据写入备份文件
                try {
                    FileWriter writer = new FileWriter(backupFile);
                    writer.append(alarmData.toString());
                    writer.flush();
                    writer.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }

            // 关闭游标
            if (cursor != null) {
                cursor.close();
            }


        }
    }


    /**
     * 获取当前电量
     *
     * @return -1 是获取当前电量失败
     */
    @RequiresApi(api = Build.VERSION_CODES.M)
    public int getCurrentBatteryLevel() {
        if (this.mContext == null) {
            Log.e("上下文为空，不执行", "请检查是否已调用setContext()");
        } else {

            // 获取系统电量管理器
            BatteryManager batteryManager = (BatteryManager) mContext.getSystemService(BATTERY_SERVICE);
            // 获取当前电量百分比
            return batteryManager.getIntProperty(BatteryManager.BATTERY_PROPERTY_CAPACITY);

        }
        return -1;
    }


    /**
     * 充电状态
     *
     * @return true  正在充电
     */
    @RequiresApi(api = Build.VERSION_CODES.M)
    public boolean getChargingInfo() {
        if (this.mContext == null) {
            Log.e("上下文为空，不执行", "请检查是否已调用setContext()");
        } else {

            // 获取系统电量管理器
            BatteryManager batteryManager = (BatteryManager) mContext.getSystemService(BATTERY_SERVICE);
            // 获取当前充电状态
            return batteryManager.isCharging();
        }
        return false;
    }


    /**
     * 内部储存空间
     *
     * @return
     */
    public String getInternalStorageSpace() {
        if (this.mContext == null) {
            Log.e("上下文为空，不执行", "请检查是否已调用setContext()");
        } else {

            // 获取内部存储空间使用情况
            File internalStoragePath = Environment.getDataDirectory();
            StatFs internalStatFs = new StatFs(internalStoragePath.getPath());

            long internalTotalSpace = internalStatFs.getTotalBytes();
            long internalFreeSpace = internalStatFs.getAvailableBytes();
            long internalUsedSpace = internalTotalSpace - internalFreeSpace;

            return "内部总存储:" + formatSize(internalTotalSpace) + ";已占用:" + formatSize(internalUsedSpace);

        }
        return "";
    }

    /**
     * SD储存空间
     *
     * @return
     */
    public String getSDStorageSpace() {
        if (this.mContext == null) {
            Log.e("上下文为空，不执行", "请检查是否已调用setContext()");
        } else {
            // 获取SD卡存储空间使用情况
            String sdCardState = Environment.getExternalStorageState();
            if (Environment.MEDIA_MOUNTED.equals(sdCardState)) {
                File externalStoragePath = Environment.getExternalStorageDirectory();
                StatFs externalStatFs = new StatFs(externalStoragePath.getPath());

                long externalTotalSpace = externalStatFs.getTotalBytes();
                long externalFreeSpace = externalStatFs.getAvailableBytes();
                long externalUsedSpace = externalTotalSpace - externalFreeSpace;

                return "SD总存储:" + formatSize(externalTotalSpace) + ";SD 卡已使用:" + formatSize(externalUsedSpace);
            }
        }

        return "";
    }


    /**
     * 进入人脸识别注册
     *
     * @return
     */
    public boolean facialRegistration() {
        if (this.mContext == null) {
            Log.e("上下文为空，不执行", "请检查是否已调用setContext()");
        } else {

        }

        return false;
    }


    /**
     * 启动寻找手机功能/关闭寻找手机功能
     *
     * @return 1 设置成功  0  设备管理员权限未激活，请先激活设备管理员权限  -1设置失败
     */
    public int  searchingPhone(boolean isOpen) {
        if (this.mContext == null) {
            Log.e("上下文为空，不执行", "请检查是否已调用setContext()");
        } else {
            DevicePolicyManager devicePolicyManager = (DevicePolicyManager) mContext.getSystemService(Context.DEVICE_POLICY_SERVICE);
            ComponentName adminComponentName = new ComponentName(mContext, RelativeLayout.class);

            if (devicePolicyManager != null && devicePolicyManager.isAdminActive(adminComponentName)) {
                if (isOpen) {
                    devicePolicyManager.setProfileName(adminComponentName, "Find My Phone");
                } else {
                    devicePolicyManager.setProfileName(adminComponentName, null);
                }
                return 1;
            } else {
                // 设备管理员权限未激活，请先激活设备管理员权限
                return 0;
            }

        }

        return -1;
    }



    /**
     * 启动寻找手机功能/关闭寻找手机功能的状态
     *
     * @return  1  寻找手机功能已启用  2寻找手机功能已禁用 0设备管理员权限未激活，请先激活设备管理员权限  -1未知
     */
    public int getSearchingPhoneState() {
        if (this.mContext == null) {
            Log.e("上下文为空，不执行", "请检查是否已调用setContext()");
        } else {
            DevicePolicyManager devicePolicyManager = (DevicePolicyManager) mContext.getSystemService(Context.DEVICE_POLICY_SERVICE);
            ComponentName adminComponentName = new ComponentName(mContext, RelativeLayout.class);

            if (devicePolicyManager != null && devicePolicyManager.isAdminActive(adminComponentName)) {
                // 设备管理员权限已激活
                boolean isFindMyDeviceEnabled = devicePolicyManager.isProfileOwnerApp(mContext.getPackageName());
                if (isFindMyDeviceEnabled) {
                    // 寻找手机功能已启用
                    return 1;
                } else {
                    // 寻找手机功能已禁用
                    return 2;
                }
            } else {
                // 设备管理员权限未激活，请先激活设备管理员权限
                return 0;
            }

        }

        return -1;
    }







    /**
     * 拿起手机唤醒荧幕 开关
     *
     * @return true 设置成功 false 设置失败
     */
    public boolean setPhoneWakeUpScreen(boolean isOpen) {
        if (this.mContext == null) {
            Log.e("上下文为空，不执行", "请检查是否已调用setContext()");
        } else {
            boolean dozeEnabled = false;
            if (isOpen) {
                // 打开拿起唤醒功能
                dozeEnabled = Settings.Secure.putInt(mContext.getContentResolver(), "doze_enabled", 1);
            } else {
                // 关闭拿起唤醒功能
                dozeEnabled = Settings.Secure.putInt(mContext.getContentResolver(), "doze_enabled", 0);
            }

            return dozeEnabled;
        }

        return false;
    }

    /**
     * 拿起手机唤醒荧幕开关状态
     *
     * @return false  关闭拿起手机唤醒荧幕  true 打开拿起手机唤醒荧幕
     */
    public boolean getPhoneWakeUpScreen() {
        if (this.mContext == null) {
            Log.e("上下文为空，不执行", "请检查是否已调用setContext()");
        } else {
            // 获取拿起唤醒功能
            int dozeEnabled = Settings.Secure.getInt(mContext.getContentResolver(), "doze_enabled", 0);
            return dozeEnabled == 1;
        }

        return false;
    }

    /**
     * 开启自动更新系统/关闭自动更新系统
     *
     * @return false  关闭自动更新系统  true 开启自动更新系统
     */
    public void setAutomaticUpdateSystem(boolean isOpen) {
        if (this.mContext == null) {
            Log.e("上下文为空，不执行", "请检查是否已调用setContext()");
        } else {

        }

    }

    /**
     * 开启自动时区/取消自动时区
     *
     * @return false  开启自动时区  true 取消自动时区
     */
    public boolean setAutomaticTimeZone(boolean isOpen) {
        if (this.mContext == null) {
            Log.e("上下文为空，不执行", "请检查是否已调用setContext()");
        } else {
            return Settings.Global.putInt(mContext.getContentResolver(), Settings.Global.AUTO_TIME_ZONE, isOpen ? 1 : 0);
        }

        return false;
    }


    /**
     * 读取系统备忘录条数
     *
     * @return 系统备忘录条数
     */
    public int getMemoCount() {
        if (this.mContext == null) {
            Log.e("上下文为空，不执行", "请检查是否已调用setContext()");
        } else {
            Cursor cursor = mContext.getContentResolver().query(Uri.parse("content://com.android.providers.userdictionary/words"), null, null, null, null);
            if (cursor != null) {
                int count = cursor.getCount();
                cursor.close();
                return count;
            } else {
                return 0;
            }
        }

        return 0;
    }

    /**
     * 取第几条备忘内容
     *
     * @return 系统备忘录条数
     */
    public String getMemoContent(int memoIndex) {
        if (this.mContext == null) {
            Log.e("上下文为空，不执行", "请检查是否已调用setContext()");
        } else {
            Cursor cursor = mContext.getContentResolver().query(Uri.parse("content://com.android.providers.userdictionary/words"), null, null, null, null);
            if (cursor != null && cursor.moveToPosition(memoIndex)) {
                @SuppressLint("Range") String memoContent = cursor.getString(cursor.getColumnIndex("word"));
                cursor.close();
                return memoContent;
            } else {
                return "";
            }
        }

        return "";
    }

    /**
     * 设置屏幕超时
     *
     * @return 超时时间
     */
    public boolean setScreenTimeout(int timeoutInMillis) {
        if (this.mContext == null) {
            Log.e("上下文为空，不执行", "请检查是否已调用setContext()");
        } else {
            // 设置屏幕超时时间（单位：毫秒）
            return Settings.System.putInt(mContext.getContentResolver(), Settings.System.SCREEN_OFF_TIMEOUT, timeoutInMillis);
        }

        return false;
    }

    /**
     * 获取当前状态 屏幕超时
     *
     * @return 设置的超时时间 毫秒
     */
    public int getScreenTimeout() {
        if (this.mContext == null) {
            Log.e("上下文为空，不执行", "请检查是否已调用setContext()");
        } else {
            // 设置屏幕超时时间（单位：毫秒）
            return Settings.System.getInt(mContext.getContentResolver(), Settings.System.SCREEN_OFF_TIMEOUT, -1);
        }

        return 0;
    }


    /**
     * 设置媒体音量为最大
     */
    public void setMaxMediaVolume() {
        if (this.mContext == null) {
            Log.e("上下文为空，不执行", "请检查是否已调用setContext()");
        } else {
            AudioManager audioManager = (AudioManager) mContext.getSystemService(Context.AUDIO_SERVICE);
            audioManager.setStreamVolume(AudioManager.STREAM_MUSIC, audioManager.getStreamMaxVolume(AudioManager.STREAM_MUSIC), 0);
        }
    }


    /**
     * 设置媒体音量为最小
     */
    public void setMinMediaVolume() {
        if (this.mContext == null) {
            Log.e("上下文为空，不执行", "请检查是否已调用setContext()");
        } else {
            AudioManager audioManager = (AudioManager) mContext.getSystemService(Context.AUDIO_SERVICE);
            audioManager.setStreamVolume(AudioManager.STREAM_MUSIC, 0, 0);
        }
    }

    /**
     * 调节媒体音量
     */
    public void seMediaVolume(int volume) {
        if (this.mContext == null) {
            Log.e("上下文为空，不执行", "请检查是否已调用setContext()");
        } else {
            AudioManager audioManager = (AudioManager) mContext.getSystemService(Context.AUDIO_SERVICE);

            int streamMaxVolume = audioManager.getStreamMaxVolume(AudioManager.STREAM_MUSIC);//音量的最大值

            audioManager.setStreamVolume(AudioManager.STREAM_MUSIC, volume * streamMaxVolume / 100, AudioManager.FLAG_PLAY_SOUND);
        }
    }


    // 设置通话音量为最大
    public void setMaxCallVolume() {
        if (this.mContext == null) {
            Log.e("上下文为空，不执行", "请检查是否已调用setContext()");
        } else {
            AudioManager audioManager = (AudioManager) mContext.getSystemService(Context.AUDIO_SERVICE);
            audioManager.setStreamVolume(AudioManager.STREAM_VOICE_CALL, audioManager.getStreamMaxVolume(AudioManager.STREAM_VOICE_CALL), 0);
        }

    }

    // 设置通话音量为最小
    public void setMinCallVolume() {
        if (this.mContext == null) {
            Log.e("上下文为空，不执行", "请检查是否已调用setContext()");
        } else {
            AudioManager audioManager = (AudioManager) mContext.getSystemService(Context.AUDIO_SERVICE);
            audioManager.setStreamVolume(AudioManager.STREAM_VOICE_CALL, 0, 0);
        }

    }

    /**
     * 调节通话音量
     */
    public void seCallVolume(int volume) {
        if (this.mContext == null) {
            Log.e("上下文为空，不执行", "请检查是否已调用setContext()");
        } else {
            AudioManager audioManager = (AudioManager) mContext.getSystemService(Context.AUDIO_SERVICE);
            int streamMaxVolume = audioManager.getStreamMaxVolume(AudioManager.STREAM_VOICE_CALL);//音量的最大值
            audioManager.setStreamVolume(AudioManager.STREAM_VOICE_CALL, volume * streamMaxVolume / 100, 0);
        }
    }


    // 设置铃声音量为最大
    public void setMaxRingVolume() {
        if (this.mContext == null) {
            Log.e("上下文为空，不执行", "请检查是否已调用setContext()");
        } else {
            AudioManager audioManager = (AudioManager) mContext.getSystemService(Context.AUDIO_SERVICE);
            audioManager.setStreamVolume(AudioManager.STREAM_RING, audioManager.getStreamMaxVolume(AudioManager.STREAM_RING), 0);
        }

    }

    // 设置铃声音量为最小
    public void setMinRingVolume() {
        if (this.mContext == null) {
            Log.e("上下文为空，不执行", "请检查是否已调用setContext()");
        } else {
            AudioManager audioManager = (AudioManager) mContext.getSystemService(Context.AUDIO_SERVICE);
            audioManager.setStreamVolume(AudioManager.STREAM_RING, 0, 0);
        }
    }

    /**
     * 调节铃声音量
     */
    public void seRingVolume(int volume) {
        if (this.mContext == null) {
            Log.e("上下文为空，不执行", "请检查是否已调用setContext()");
        } else {
            AudioManager audioManager = (AudioManager) mContext.getSystemService(Context.AUDIO_SERVICE);
            int streamMaxVolume = audioManager.getStreamMaxVolume(AudioManager.STREAM_RING);//音量的最大值
            audioManager.setStreamVolume(AudioManager.STREAM_RING, volume * streamMaxVolume / 100, 0);
        }
    }


    // 设置闹钟音量为最大
    public void setMaxAlarmVolume() {
        if (this.mContext == null) {
            Log.e("上下文为空，不执行", "请检查是否已调用setContext()");
        } else {
            AudioManager audioManager = (AudioManager) mContext.getSystemService(Context.AUDIO_SERVICE);
            audioManager.setStreamVolume(AudioManager.STREAM_ALARM, audioManager.getStreamMaxVolume(AudioManager.STREAM_ALARM), 0);
        }

    }

    // 设置闹钟音量为最小
    public void setMinAlarmVolume() {
        if (this.mContext == null) {
            Log.e("上下文为空，不执行", "请检查是否已调用setContext()");
        } else {
            AudioManager audioManager = (AudioManager) mContext.getSystemService(Context.AUDIO_SERVICE);
            audioManager.setStreamVolume(AudioManager.STREAM_ALARM, 0, 0);
        }
    }

    /**
     * 调节闹钟音量
     */
    public void seAlarmVolume(int volume) {
        if (this.mContext == null) {
            Log.e("上下文为空，不执行", "请检查是否已调用setContext()");
        } else {
            AudioManager audioManager = (AudioManager) mContext.getSystemService(Context.AUDIO_SERVICE);
            int streamMaxVolume = audioManager.getStreamMaxVolume(AudioManager.STREAM_ALARM);//音量的最大值
            audioManager.setStreamVolume(AudioManager.STREAM_ALARM, volume * streamMaxVolume / 100, 0);
        }
    }

    /**
     * 来电振动设置（一律不振动）
     */
    public void setRingerVibrateOff() {

        if (this.mContext == null) {
            Log.e("上下文为空，不执行", "请检查是否已调用setContext()");
        } else {
            AudioManager audioManager = (AudioManager) mContext.getSystemService(Context.AUDIO_SERVICE);
            audioManager.setRingerMode(AudioManager.RINGER_MODE_SILENT);
        }

    }

    /**
     * 来电振动设置（一律振动）
     */
    public void setRingerVibrateOn() {
        if (this.mContext == null) {
            Log.e("上下文为空，不执行", "请检查是否已调用setContext()");
        } else {
            AudioManager audioManager = (AudioManager) mContext.getSystemService(Context.AUDIO_SERVICE);
            audioManager.setRingerMode(AudioManager.RINGER_MODE_VIBRATE);
        }
    }

    /**
     * 来电振动设置（先振动再铃声渐大）
     */
    @RequiresApi(api = Build.VERSION_CODES.O)
    public void setRingerVibrateRampUp() {

        if (this.mContext == null) {
            Log.e("上下文为空，不执行", "请检查是否已调用setContext()");
        } else {
            AudioManager audioManager = (AudioManager) mContext.getSystemService(Context.AUDIO_SERVICE);
            audioManager.setRingerMode(AudioManager.RINGER_MODE_NORMAL);
            Vibrator vibrator = (Vibrator) mContext.getSystemService(Context.VIBRATOR_SERVICE);
            long[] pattern = {0, 500, 250, 500}; // 震动时间和等待时间交替的数组，单位毫秒
            vibrator.vibrate(VibrationEffect.createWaveform(pattern, -1));
        }
    }



    public static String formatSize(long size) {
        if (size <= 0) return "0";
        final String[] units = new String[]{"B", "KB", "MB", "GB", "TB"};
        int digitGroups = (int) (Math.log10(size) / Math.log10(1024));
        return new DecimalFormat("#,##0.#").format(size / Math.pow(1024, digitGroups)) + " " + units[digitGroups];
    }
}
